<?php
class Cache
{
	public $vars = array();
	public $var_expires = array();
	public $is_modified = false;

	public $cache_dir = '';

	/**
	* Set cache path
	*/
	function __construct()
	{
		$this->cache_dir = DATA_DIR . 'cache/';
	}

	/**
	* Load global cache
	*/
	function load()
	{
		if (file_exists($this->cache_dir . 'data_global.php')) {
			@include($this->cache_dir . 'data_global.php');
		} else {
			return false;
		}

		return true;
	}

	/**
	* Unload cache object
	*/
	function unload()
	{
		$this->save();
		unset($this->vars);
		unset($this->var_expires);
		unset($this->sql_rowset);
		unset($this->sql_row_pointer);

		$this->vars = array();
		$this->var_expires = array();
		$this->sql_rowset = array();
		$this->sql_row_pointer = array();
	}

	/**
	* Save modified objects
	*/
	function save()
	{
		if (!$this->is_modified) {
			return;
		}
		if ($fp = @fopen($this->cache_dir . 'data_global.php', 'wb')) {
			@flock($fp, LOCK_EX);
			fwrite($fp, "<?php\n\$this->vars = " . var_export($this->vars, true) . ";\n\n\$this->var_expires = " . var_export($this->var_expires, true) . "\n?>");
			@flock($fp, LOCK_UN);
			fclose($fp);

			@chmod($this->cache_dir . 'data_global.php', 0666);
		} else {
			// Now, this occurred how often? ... phew, just tell the user then...
			if (!@is_writable($this->cache_dir)) {
				trigger_error($this->cache_dir . ' is NOT writable.', E_USER_ERROR);
			}

			trigger_error('Not able to open ' . $this->cache_dir . 'data_global.php', E_USER_ERROR);
		}

		$this->is_modified = false;
	}

	/**
	* Tidy cache
	*/
	function tidy()
	{
		$dir = @opendir($this->cache_dir);

		if (!$dir) {
			return;
		}

		while (($entry = readdir($dir)) !== false) {
			if (!preg_match('/^(sql_|data_(?!global))/', $entry)) {
				continue;
			}

			$expired = true;
			@include($this->cache_dir . $entry);
			if ($expired) {
				$this->removeFile($this->cache_dir . $entry);
			}
		}
		closedir($dir);

		if (file_exists($this->cache_dir . 'data_global.php')) {
			if (!sizeof($this->vars)) {
				$this->load();
			}

			foreach ($this->var_expires as $var_name => $expires) {
				if (time() > $expires) {
					$this->destroy($var_name);
				}
			}
		}
		
		set_config('cache_last_gc', time(), true);
	}

	/**
	* Get saved cache object
	*/
	function get($var_name)
	{
		if ($var_name[0] == '_') {
			if (!$this->_exists($var_name)) {
				return false;
			}

			@include($this->cache_dir . "data{$var_name}.php");
			return (isset($data)) ? $data : false;
		} else {
			return ($this->_exists($var_name)) ? $this->vars[$var_name] : false;
		}
	}

	/**
	* Put data into cache
	*/
	function put($var_name, $var, $ttl = 31536000)
	{
		if ($var_name[0] == '_') {
			if ($fp = @fopen($this->cache_dir . "data{$var_name}.php", 'wb')) {
				@flock($fp, LOCK_EX);
				fwrite($fp, "<?php\n\$expired = (time() > " . (time() + $ttl) . ") ? true : false;\nif (\$expired) { return; }\n\n\$data = " . var_export($var, true) . ";\n?>");
				@flock($fp, LOCK_UN);
				fclose($fp);

				@chmod($this->cache_dir . "data{$var_name}.php", 0666);
			}
		} else {
			$this->vars[$var_name] = $var;
			$this->var_expires[$var_name] = time() + $ttl;
			$this->is_modified = true;
		}
	}

	/**
	* Purge cache data
	*/
	function purge()
	{
		// Purge all phpbb cache files
		$dir = @opendir($this->cache_dir);

		if (!$dir) {
			return;
		}

		while (($entry = readdir($dir)) !== false) {
			if (strpos($entry, 'sql_') !== 0 && strpos($entry, 'data_') !== 0 && strpos($entry, 'ctpl_') !== 0 && strpos($entry, 'tpl_') !== 0) {
				continue;
			}

			$this->removeFile($this->cache_dir . $entry);
		}
		closedir($dir);

		unset($this->vars);
		unset($this->var_expires);
		unset($this->sql_rowset);
		unset($this->sql_row_pointer);

		$this->vars = array();
		$this->var_expires = array();
		$this->sql_rowset = array();
		$this->sql_row_pointer = array();

		$this->is_modified = false;
	}

	/**
	* Destroy cache data
	*/
	function destroy($var_name, $table = '')
	{
		if ($var_name == 'sql' && !empty($table)) {
			if (!is_array($table)) {
				$table = array($table);
			}

			$dir = @opendir($this->cache_dir);

			if (!$dir) {
				return;
			}

			while (($entry = readdir($dir)) !== false) {
				if (strpos($entry, 'sql_') !== 0) {
					continue;
				}

				// The following method is more failproof than simply assuming the query is on line 3 (which it should be)
				$check_line = @file_get_contents($this->cache_dir . $entry);

				if (empty($check_line)) {
					continue;
				}

				// Now get the contents between /* and */
				$check_line = substr($check_line, strpos($check_line, '/* ') + 3, strpos($check_line, ' */') - strpos($check_line, '/* ') - 3);

				$found = false;
				foreach ($table as $check_table) {
					// Better catch partial table names than no table names. ;)
					if (strpos($check_line, $check_table) !== false) {
						$found = true;
						break;
					}
				}

				if ($found) {
					$this->removeFile($this->cache_dir . $entry);
				}
			}
			closedir($dir);

			return;
		}

		if (!$this->_exists($var_name)) {
			return;
		}

		if ($var_name[0] == '_') {
			$this->removeFile($this->cache_dir . 'data' . $var_name . ".php", true);
		} else if (isset($this->vars[$var_name])) {
			$this->is_modified = true;
			unset($this->vars[$var_name]);
			unset($this->var_expires[$var_name]);

			// We save here to let the following cache hits succeed
			$this->save();
		}
	}

	/**
	* Check if a given cache entry exist
	*/
	function _exists($var_name)
	{
		if ($var_name[0] == '_') {
			return file_exists($this->cache_dir . 'data' . $var_name . ".php");
		} else {
			if (!sizeof($this->vars)) {
				$this->load();
			}

			if (!isset($this->var_expires[$var_name])) {
				return false;
			}
			
			return (time() > $this->var_expires[$var_name]) ? false : isset($this->vars[$var_name]);
		}
	}

	/**
	* Removes/unlinks file
	*/
	function removeFile($filename, $check = false)
	{
		if ($check && !@is_writeable($this->cache_dir)) {
			// E_USER_ERROR - not using language entry - intended.
			trigger_error('Unable to remove files within ' . $this->cache_dir . '. Please check directory permissions.', E_USER_ERROR);
		}

		return @unlink($filename);
	}

}
?>